package com.jse.plug;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.crypto.dsig.SignatureMethod;

import com.jse.util.Http;
import com.jse.util.JseMap;

public class AliyunApi {
	
	private static final String ENCODE_TYPE = "UTF-8";
    private static String percentEncode(String value) throws UnsupportedEncodingException {
        if (value == null) return null;
        return URLEncoder.encode(value, ENCODE_TYPE).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }
    private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    private static String formatIso8601Date(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
        df.setTimeZone(new SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }
	
    /**
     * 
     * @param action "GetVideoList"
     * @param map 如列表 		params.put("Action", action);//视频列表
		params.put("Status", "Normal");//视频列表
		//params.put("CateId", 999);
		//params.put("SortBy", "CreationTime:Asc");
		params.put("PageNo", 1);//视频列表
		params.put("PageSize", 100);//视频列表
		
     * @return
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
	public static String exec(String action,HashMap<String, Object> map) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
		 final String HTTP_METHOD = "GET";
		JseMap params = new JseMap();
		params.put("Format", "JSON");//视频列表
		params.put("Version", "2017-03-21");//视频列表
		params.put("AccessKeyId", "LTAI8MDgUrXvLBpl");//视频列表
		params.put("SignatureMethod", "HMAC-SHA1");//视频列表
		params.put("Timestamp", formatIso8601Date(new Date()));//视频列表
		params.put("SignatureVersion", "1.0");//视频列表
		params.put("SignatureNonce", UUID.randomUUID().toString());
		params.put("Action", action);//视频列表
		if(map!=null)
		params.putAll(map);
		List<String> sortedKeys = new ArrayList<String>(params.keySet());
	    Collections.sort(sortedKeys);
	    // 生成stringToSign字符
	    final String SEPARATOR = "&";
	    final String EQUAL = "=";
	    StringBuilder stringToSign = new StringBuilder();
	    stringToSign.append(HTTP_METHOD).append(SEPARATOR);
	    stringToSign.append(percentEncode("/")).append(SEPARATOR);
	    StringBuilder canonicalizedQueryString = new StringBuilder();
	    for (String key : sortedKeys) {
	        // 此处需要对key和value进行编码
	        String value = params.getString(key);
	        canonicalizedQueryString.append(SEPARATOR).append(percentEncode(key)).append(EQUAL).append(percentEncode(value));
	    }
	    // 此处需要对canonicalizedQueryString进行编码
	       stringToSign.append(percentEncode(canonicalizedQueryString.toString().substring(1)));
		
		final String ALGORITHM = "HmacSHA1";
	    final String secret = "OlEapJaG8KtKjqqPpLadX2b3zQ3p94";//此处请替换成您的AccessKeySecret
	    SecretKey key = new SecretKeySpec((secret + SEPARATOR).getBytes(ENCODE_TYPE), SignatureMethod.HMAC_SHA1);
	    Mac mac = Mac.getInstance(ALGORITHM);
	    mac.init(key);
	    String signature = URLEncoder.encode(new String(Base64.getEncoder().encode(mac.doFinal(stringToSign.toString().getBytes(ENCODE_TYPE))),
	ENCODE_TYPE), ENCODE_TYPE);
	    // 生成请求URL
	    StringBuilder requestURL;
	    requestURL = new StringBuilder("http://vod.cn-shanghai.aliyuncs.com?");
	    requestURL.append(URLEncoder.encode("Signature", ENCODE_TYPE)).append("=").append(signature);
	    for (Map.Entry<String, Object> e : params.entrySet()) {
	    requestURL.append("&").append(percentEncode(e.getKey())).append("=").append(percentEncode(e.getValue().toString()));
	    }
//	    System.err.println(requestURL);
	    return Http.get(requestURL.toString());
//	    NutMap map=Json.fromJson(NutMap.class,resp.getContent());
//	    //单集视频
//	    List list=map.getAs("VideoList", NutMap.class).getList("Video", ArrayList.class);
	}
}